# /usr/bin/python
# -*- coding: utf-8 -*-

import os,sys
BASE_DIR = os.path.dirname(os.path.abspath(os.curdir))
sys.path.append(BASE_DIR)
import re
from models.MySQL import MySQL
from models.Zabbix import ZBX
from conf.setting import templates,key_dict,func_dict
from util.log import get_stream_logger
from util.key_translate import key_trn

logger = get_stream_logger("add_strategy")

Z = ZBX()
templates = Z.get_template(host=templates)

for template in templates:
    with MySQL() as cur:
        cmd = "SELECT id from tpl WHERE tpl_name='%s'"%template['name']
        templateid = cur.search(cmd)[0][0]

    triggers = Z.get_trigger(templateids=template['templateid'])
    for trigger in triggers:
        triggerid = trigger['triggerid']
        itemid = int(trigger['functions'][0]['itemid'])
        function = trigger['functions'][0]['function']
        parameter = trigger['functions'][0]['parameter'].split(',')[0]

        if parameter == 0 or parameter == '0':
            parameter = '#1'
        elif re.match(r"\d+m",parameter):
            parameter = '#' + parameter.replace('m','')

        expression = trigger['expression'].split('}')[1]
        try:
            groupdict = re.match(r"(?P<op>=|<|>|<=|>=)(?P<value>\d+).*",expression).groupdict()
        except AttributeError:
            logger.warn("Zabbix expression %s is illegal"%expression)
            continue

        value = groupdict["value"]
        op = groupdict["op"].strip()
        if op == '=' :
            op = '=='

        description = trigger['description']
        key = Z.get_item(itemids=itemid)[0]['key_']

        try:
            res_key = key_trn(key)
            if isinstance(res_key,list):
                new_key = res_key[0]
                tag = res_key[1]
            else:
                new_key = res_key
                tag = ''

        except KeyError:
            logger.warn("Falcon not support the key %s from trigger %s from %s"%\
                    (key,description,template['name']))
            continue
        
        try:
            new_function = func_dict[function] + '(' + parameter + ')'
        except KeyError:
            logger.warn("Falcon not suppert the func %s from trigger %s from %s"%\
                    (function,description,template['name']))
            continue

        if new_key != "cpu":
            with MySQL() as cur:
                check_cmd = "SELECT  * FROM strategy WHERE metric='%s' and tpl_id='%s' and op='%s' and right_value='%s' and note='%s'"%(new_key,templateid,op,value,description)
                check_res = cur.cur.execute(check_cmd)
                if check_res == 0:
                    insert_cmd = "INSERT INTO strategy VALUES (null,'%s','%s',3,0,'%s','%s','%s','%s','','','%s')"%\
                            (new_key,tag,new_function,op,value,description,templateid)

                    res = cur.update(insert_cmd)
                    if  res !=  1:
                        logger.error("Trigger  %s from %s insert failed"%(description,template['name']))
                else:
                    logger.info("Falcon has the same or smilar metric, cannot support this grained on trigger:%s from template:%s"%\
                            (description,template['name']))
        else:
            continue
